// mongoose.js - Mongoose 数据库连接
const mongoose = require('mongoose');
const config = require('./config');

// 连接数据库
mongoose.connect(config.MONGO_URI, config.OPTIONS)
  .then(() => {
    console.log('✅ MongoDB 数据库连接成功');
  })
  .catch(err => {
    console.error('❌ MongoDB 连接错误:', err.message);
    // 严重错误，退出应用
    process.exit(1);
  });

// 监听连接事件
mongoose.connection.on('connected', () => {
  console.log(`🔌 Mongoose 已连接到: ${config.MONGO_URI}`);
});

mongoose.connection.on('error', (err) => {
  console.error('🔥 Mongoose 连接错误:', err.message);
});

mongoose.connection.on('disconnected', () => {
  console.log('🔌 Mongoose 连接已断开');
});

// 应用终止时关闭连接
process.on('SIGINT', async () => {
  await mongoose.connection.close();
  console.log('Mongoose 连接已关闭 (应用终止)');
  process.exit(0);
});

module.exports = mongoose; 